/*
    Copyright 2006-2011 Patrik Jonsson, sunrise@familjenjonsson.org

    This file is part of Sunrise.

    Sunrise is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    Sunrise is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Sunrise.  If not, see <http://www.gnu.org/licenses/>.

*/

/// \file
/// An executable to write an image as a compressed FITS file.
/// \ingroup cmprauxfits

// $Id$

/** \defgroup cmprauxfits Auxiliary compressed FITS writer (cmprauxfits)

    This is an external executable used by mcrx to write the
    tile-compressed data cubes generated by the nonscatter stage
    simultaneously.  Because cfitsio is not thread-safe, this must be
    done in separate processes.  */

#include <fstream>
#include <iostream>
#include <vector>
#include "fitsio.h"
#include <sys/shm.h> 
#include <cassert>

using namespace std;

/** \ingroup cmprauxfits
    This executable takes the data for an image array from a shared
    memory segment and writes it to a FITS file using the cfitsio
    "tile-compression" algorithm.  This is used by
    mcrx::full_sed_emergence::write_images which starts a number of
    these processes to write all the cameras in parallel. */
int main (int argc, char**argv)
{
  if (argc != 2) {
    cerr << "Usage: cmprauxfits <fits_file> " << endl;
    exit (1);
  }

  char*  fits_file_name = argv [1];
  cout << "Writing FITS file " << fits_file_name << endl;

  // write FITS file
  fitsfile *file;
  int status = 0;
  fits_open_file (&file, fits_file_name, READWRITE, &status);
  fits_movabs_hdu (file, 2, 0, &status);
  long naxes [3];
  fits_get_img_size (file, 3, naxes, &status);

  const long size = naxes [0]*naxes [1]*naxes [2];
  //float* data=new float[slice];

  // attached to shared memory
  key_t key = ftok (argv [1], 'A');
  const int shared_ID = shmget (key, size,0644);
  float* shared_data = reinterpret_cast<float*> (shmat (shared_ID, 0,0));
  assert (shared_data);

  long fpixel [] = {1,1,1};
  fits_write_pix (file, TFLOAT, fpixel, size, shared_data, &status);
  if (status) fits_report_error (stderr, status);
  fits_close_file (file, &status);
  
  // detach from shared memory
  shmdt (shared_data);
}
